<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :before-close="handleCancel"
      :close-on-click-modal="false"
      center
      width="50%"
      class="dialog-s"
      top="1vh"
    >
      <el-form ref="editFormRef" :model="editForm" :rules="rules" label-width="100px" size="mini">
        <el-row>
          <el-col :span="7">
            <el-form-item label="告警类型" prop="strategyId">
              <el-select
                :disabled="!isAdd"
                class="tactics-key"
                @change="alarmTypeChange"
                placeholder="请选择告警类型"
                v-model="editForm.strategyId"
              >
                <el-option
                  v-for="item in alarmTypeList"
                  :key="item.strategyId"
                  :label="item.alarmType"
                  :value="item.strategyId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="7" :offset="3">
            <el-form-item label="监测设备" prop="eqptTypeName">
              <span class="highlight"
                >{{ editForm.eqptTypeName }} - {{ editForm.productName }}</span
              >
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="监测字段" prop="eqptAttribute">
              <span class="highlight">{{ editForm.eqptAttribute }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <div v-for="(e, index) in editForm.strategyConditionList" :key="index">
          <div class="line"></div>
          <el-form-item
            label="告警等级"
            ref="alarmLevelItem"
            :prop="'strategyConditionList.' + index + '.alarmLevel'"
            :rules="{
              required: false,
              validator: validLeastOne,
              trigger: 'change'
            }"
          >
            <el-checkbox v-model="e.alarmLevel" :true-label="String(index + 1)" false-label="0">
              {{ getLabel(index) }}
            </el-checkbox>
          </el-form-item>

          <div v-if="e.alarmLevel !== '0'">
            <el-row>
              <el-col class="cus-col-width">
                <el-form-item
                  label="触发条件"
                  :prop="'strategyConditionList.' + index + '.alarmCondition'"
                  :rules="{
                    required: true,
                    message: '请选择触发条件',
                    trigger: 'change'
                  }"
                >
                  <el-select class="tactics-key" v-model="e.alarmCondition">
                    <el-option
                      v-for="item in getListForAttributeType(editForm.attributeType)"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col class="cus-col-width cus-col-margin">
                <el-form-item
                  v-if="editForm.attributeType === '2'"
                  label=""
                  :prop="'strategyConditionList.' + index + '.alarmValue'"
                  :rules="{
                    required: true,
                    message: '请选择值!',
                    trigger: 'change'
                  }"
                >
                  <el-select class="tactics-key" placeholder="请输入值" v-model="e.alarmValue">
                    <el-option
                      v-for="item in booleanValue"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item
                  v-else
                  label=""
                  :prop="'strategyConditionList.' + index + '.alarmValue'"
                  :rules="{
                    required: true,
                    validator: editForm.attributeType === '0' ? validNumber : validString,
                    trigger: 'change'
                  }"
                >
                  <el-input
                    class="tactics-key"
                    placeholder="请输入值"
                    v-model="e.alarmValue"
                  ></el-input>
                  <span style="margin-left: 10px">{{ editForm.attributeSuffix }}</span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row v-if="editForm.attributeType === '0'">
              <el-col class="cus-col-width">
                <el-form-item
                  label="(同时满足)"
                  :prop="'strategyConditionList.' + index + '.alarmCondition2'"
                  :rules="{
                    required: false,
                    message: '请选择触发条件',
                    trigger: 'change'
                  }"
                >
                  <el-select clearable class="tactics-key" v-model="e.alarmCondition2">
                    <el-option
                      v-for="item in getListForAttributeType(editForm.attributeType)"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col class="cus-col-width cus-col-margin">
                <el-form-item
                  label=""
                  :prop="'strategyConditionList.' + index + '.alarmValue2'"
                  :rules="{
                    required: false,
                    validator: validNumberAndEmpty,
                    trigger: 'change'
                  }"
                >
                  <el-input
                    class="tactics-key"
                    placeholder="请输入值"
                    v-model="e.alarmValue2"
                  ></el-input>
                  <span style="margin-left: 10px">{{ editForm.attributeSuffix }}</span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item
              label="站内消息通知"
              :prop="'strategyConditionList.' + index + '.sendStation'"
            >
              <el-radio-group v-model="e.sendStation">
                <el-radio :label="1">所有告警发消息</el-radio>
                <el-radio :label="0">所有告警不发消息</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="短信消息通知"
              :prop="'strategyConditionList.' + index + '.sendMsg'"
            >
              <el-radio-group v-model="e.sendMsg">
                <el-radio :label="1">所有告警发短信</el-radio>
                <el-radio :label="0">所有告警不发短信</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="模板参数" :prop="'strategyConditionList.' + index + '.sendMsg'">
              <div class="muBan">
                <div
                  v-for="(item, index1) in listData"
                  v-bind:key="index1"
                  class="item-list"
                  @click="selectMB(item, index)"
                >
                  {{ item }}
                </div>
              </div>
            </el-form-item>

            <el-form-item
              label="告警模板"
              :prop="'strategyConditionList.' + index + '.contentTemplate'"
              :rules="{
                required: true,
                message: '请输入值!'
              }"
            >
              <el-input
                type="textarea"
                :autosize="{ minRows: 2 }"
                placeholder="请输入内容"
                v-model="e.contentTemplate"
                @input="changeTemplate($event, index)"
              >
              </el-input>
            </el-form-item>

            <el-form-item
              label="告警内容示例"
              :prop="'strategyConditionList.' + index + '.contentTemplate'"
            >
              {{ e.content }}
            </el-form-item>

            <el-form-item
              label="是否转为工单"
              :prop="'strategyConditionList.' + index + '.changeOrder'"
            >
              <el-checkbox v-model="e.changeOrder" :true-label="1" :false-label="0">
                该类告警转为工单
              </el-checkbox>
            </el-form-item>
          </div>

          <!-- <div v-if="e.alarmLevel !== '0' && e.changeOrder"> -->
          <div v-if="e.alarmLevel !== '0'">
            <div class="order-tip" v-if="e.changeOrder">
              温馨提示: 满足该条件的告警将转为工单, 转为工单的告警消息通知策略根据对应的工单进行设计
            </div>

            <el-row>
              <el-col class="cus-col-width">
                <el-form-item
                  label="工单类型"
                  :prop="'strategyConditionList.' + index + '.orderType'"
                  :rules="{
                    required: true,
                    message: '请选择工单类型!',
                    trigger: 'change'
                  }"
                >
                  <el-select placeholder="请选择工单类型" class="tactics-key" v-model="e.orderType">
                    <el-option
                      v-for="item in orderTypeList"
                      :key="item.typeNo"
                      :label="item.typeName"
                      :value="item.typeNo"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col class="cus-col-width cus-col-margin">
                <el-form-item
                  label=""
                  :prop="'strategyConditionList.' + index + '.orderLevel'"
                  :rules="{
                    required: true,
                    message: '请选择工单等级程度!',
                    trigger: 'change'
                  }"
                >
                  <el-select
                    placeholder="请选择工单等级程度"
                    class="tactics-key"
                    v-model="e.orderLevel"
                  >
                    <el-option
                      v-for="item in orderLevelList"
                      :key="item.key"
                      :label="item.value"
                      :value="String(item.key)"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col class="cus-col-width">
                <el-form-item
                  label="冻结期限"
                  :prop="'strategyConditionList.' + index + '.frozenTerm'"
                  :rules="{
                    required: true,
                    validator: validPositiveInteger,
                    trigger: 'change'
                  }"
                >
                  <el-input
                    class="tactics-key"
                    placeholder="请输入冻结期限"
                    v-model="e.frozenTerm"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col class="cus-col-width cus-col-margin">
                <el-form-item
                  label=""
                  :prop="'strategyConditionList.' + index + '.frozenTermSuffix'"
                  :rules="{
                    required: true,
                    message: '请选择单位!',
                    trigger: 'change'
                  }"
                >
                  <el-select class="tactics-key" v-model="e.frozenTermSuffix">
                    <el-option
                      v-for="item in timeList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                  <span style="margin-left: 10px">内只转一次工单</span>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleOk(1)" size="small">确 定</el-button>
        <el-button @click="handleAgain" icon="el-icon-plus" type="primary" size="small"
          >继续新增</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import pick from 'lodash.pick'
import { getOrderType, getOrderLevel, addTactics, modifyTactics, searchTactics } from '../js/alarm'
import { validNumber, validNumberAndEmpty, validString, validPositiveInteger } from '../js/validate'
import {
  stringCondition,
  numberCondition,
  booleanCondition,
  booleanValue,
  alarmLevelList
} from '../js/constants'
// import NotFoundVue from '@/views/NotFound.vue'

/**
 * 告警策略 新增编辑
 * @description 根据设备类型判断监测字段的类型(0：数值，1：字符，2：布尔)。
 * @description1 根据监测字段的类型, 触发条件和触发值不同显示
 * @description2 strategyConditionList每次弹框为其赋值(v-if导致resetFields未生效)
 */
let templateObj = {
  alarmLevel: '0',
  alarmCondition: '',
  alarmCondition2: '',
  alarmValue: '',
  alarmValue2: '',
  sendStation: 1,
  sendMsg: 0,
  changeOrder: 0,
  orderType: '',
  orderLevel: '',
  frozenTerm: '',
  frozenTermSuffix: '',
  contentTemplate: '',
  content: ''
}
export default {
  name: 'TacticsModal',
  data () {
    return {
      title: '',
      dialogVisible: false, // 编辑弹窗
      disabled: true,
      editForm: {
        alarmType: '',
        strategyId: '',
        eqptTypeId: '',
        eqptTypeName: '',
        judgeId: '',
        productName: '',
        eqptAttribute: '',
        eqptAttributeKey: '',
        attributeType: '', // 属性的类型(0：数值，1：字符，2：布尔)
        attributeSuffix: '', // 属性的单位
        strategyConditionList: [] // 告警等级数组
      },
      model: {},
      rules: {
        alarmLevel: [{ required: true, message: '请输入告警类型名称!' }],
        strategyId: [{ required: true, message: '请选择告警类型!' }],
        frequency: [{ required: true, validator: validPositiveInteger, trigger: 'change' }]
      },
      timeList: [
        { label: '秒', value: 's' },
        { label: '分', value: 'm' },
        { label: '时', value: 'h' }
      ],
      orderTypeList: [],
      orderLevelList: [],
      stringCondition,
      numberCondition,
      booleanCondition,
      booleanValue,
      isAdd: false,
      listData: [
        '@{监测设备}',
        '@{监测字段}',
        '@{监测单位}',
        '@{触发条件一}',
        '@{触发值一}',
        '@{触发条件二}',
        '@{触发值二}',
        '@{异常值}'
      ],
      textarea2: []
    }
  },
  props: {
    alarmTypeList: {
      type: Array,
      required: true,
      default: () => []
    }
  },

  mounted () {
    this.getOrderType()
    this.getOrderLevel()
  },

  // computed:{
  //   watchInputData(){ return this.editForm.strategyConditionList[0].contentTemplate }
  // },
  watch: {
    // textarea2(val,oldVal){
    //   if(oldVal.charAt(oldVal.length-1) === '}') {
    //     var index = val.lastIndexOf('@')
    //     var newString = val.slice(index).concat('}')
    //     console.log(this.listData.indexOf(newString), 90)
    //     if (this.listData.indexOf(newString) > -1) {
    //       this.textarea2 = val.slice(0, index)
    //     }
    //   }
    //   this.textArea = this.textarea2.replace(/\@{监测设备}/g, (this.editForm.eqptTypeName + '-' + this.editForm.productName));
    //   this.textArea = this.textArea.replace(/\@{监测字段}/g, this.editForm.eqptAttribute);
    //   this.textArea = this.textArea.replace(/\@{监测单位}/g, this.editForm.eqptAttribute);
    //   this.textArea = this.textArea.replace(/\@{触发条件一}/g, this.editForm.eqptAttribute);
    //   this.textArea = this.textArea.replace(/\@{触发值一}/g, this.editForm.eqptAttribute);
    //   this.textArea = this.textArea.replace(/\@{触发条件二}/g, this.editForm.eqptAttribute);
    //   this.textArea = this.textArea.replace(/\@{触发值二}/g, '条件');
    //   this.textArea = this.textArea.replace(/\@{异常值}/g, '条件');
    //   console.log(this.textArea, 999)
    // }
  },
  methods: {
    validNumber,
    validNumberAndEmpty,
    validString,
    validPositiveInteger,
    // 触发条件
    getListForAttributeType (val) {
      if (val === '0') return numberCondition
      if (val === '1') return stringCondition
      if (val === '2') return booleanCondition
    },
    // 新增
    add () {
      this.edit({})
    },
    // 编辑
    edit (record) {
      this.dialogVisible = true
      this.dataToForm(record)
    },

    // 存在策略时, 表单赋值
    dataToForm (record) {
      ;[1, 2, 3].forEach((e, i) => {
        this.$set(this.editForm.strategyConditionList, i, Object.assign({}, templateObj))
      })
      if (!this.isAdd) {
        this.title = '编辑告警策略'
        this.$nextTick(() => {
          let { strategyConditionList, ...otherParams } = record
          this.editForm = Object.assign(this.editForm, otherParams)
          strategyConditionList.forEach((item, index) => {
            Object.assign(this.editForm.strategyConditionList[+item.alarmLevel - 1], item)
            this.changeTemplate(item.contentTemplate, index)
          })
        })
      } else {
        this.title = '添加告警策略'
      }
    },

    // 提交表单  // type: 1:  保存  2: 继续新增
    handleOk (type) {
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          let values = JSON.parse(JSON.stringify(this.editForm))
          values.strategyConditionList = values.strategyConditionList.filter(
            (e) => e.alarmLevel !== '0'
          )
          values.strategyConditionList.forEach((r) => {
            r.id = undefined
            // if (r.changeOrder === 0) {
            //   r.orderType = ''
            //   r.orderLevel = ''
            //   r.frozenTerm = ''
            //   r.frozenTermSuffix = ''
            // }
          })
          let res, msg
          if (this.isAdd) {
            res = await addTactics(values)
            msg = '保存成功！'
          } else {
            res = await modifyTactics(Object.assign(values))
            msg = '修改成功！'
          }
          if (res.code === 0) {
            this.$message.success(msg)
          } else {
            this.$message.warning(res.msg)
          }
          this.$emit('ok')
          if (type === 1) {
            this.handleCancel()
          } else {
            this.emptyData()
            this.isAdd = true
            this.dataToForm()
          }
        }
      })
    },

    // 获取工单类型
    async getOrderType () {
      const { code, data, msg } = await getOrderType()
      if (code === 0) {
        this.orderTypeList = data
      } else {
        this.$message.warning(msg)
      }
    },

    // 获取工单等级
    async getOrderLevel () {
      const { code, data, msg } = await getOrderLevel()
      if (code === 0) {
        this.orderLevelList = data
      } else {
        this.$message.warning(msg)
      }
    },

    // 为新增时, 赋值数据且清空条件
    initData (val) {
      this.isAdd = true
      this.title = '添加告警策略'
      const params = this.alarmTypeList.filter((e) => e.strategyId === val)[0]
      Object.assign(
        this.editForm,
        pick(
          params,
          'alarmType',
          'eqptTypeId',
          'eqptTypeName',
          'judgeId',
          'productName',
          'eqptAttribute',
          'eqptAttributeKey',
          'attributeSuffix',
          'attributeType'
        )
      )
      console.log(this.editForm.strategyConditionList, 998)
      this.editForm.strategyConditionList.forEach((e) => {
        e.alarmCondition = ''
        e.alarmCondition2 = ''
        e.alarmValue = ''
        e.alarmValue2 = ''
        e.contentTemplate = ''
      })
      this.$nextTick(() => {
        this.$refs.editFormRef.clearValidate()
      })
    },

    /**
     * @description: 告警类型改变
     * @description: 改变查询是否有存在的策略, 有: 清空数据, 重新赋值, 调用编辑接口 无: 手动赋值, 并且清空条件, 调用新增接口
     */
    async alarmTypeChange (val) {
      const params = {
        current: 1,
        pageSize: 10,
        strategyId: val
      }
      const res = await searchTactics(Object.assign({}, params))
      if (res.code === 0) {
        if (res.data && res.data.records.length !== 0) {
          this.isAdd = false
          this.emptyData()
          this.dataToForm(res.data.records[0])
        } else {
          this.initData(val)
        }
      } else {
        this.initData(val)
        this.$message.warning(res.msg)
      }
    },

    getLabel (val) {
      return this.$base.constFormatter(alarmLevelList, String(val + 1))
    },

    // 自定义校验至少选择一个告警等级
    validLeastOne (rule, value, callback) {
      let havaLeastOne = this.editForm.strategyConditionList.filter(
        (e) => e.alarmLevel !== '0'
      ).length
      if (havaLeastOne > 0) {
        this.$refs.alarmLevelItem.forEach((e) => e.clearValidate())
        callback()
      } else {
        callback(new Error('请至少选择一个告警等级!'))
      }
    },

    // 继续新增
    handleAgain () {
      this.handleOk(2)
    },

    // 取消
    handleCancel () {
      this.dialogVisible = false
      this.isAdd = false
      this.emptyData()
    },

    // 清空数据
    emptyData () {
      this.$refs.editFormRef.resetFields()
      this.editForm.alarmType = ''
      this.editForm.eqptTypeId = ''
      this.editForm.eqptAttributeKey = ''
      this.editForm.judgeId = ''
      this.editForm.productName = ''
      this.editForm.attributeType = ''
      this.editForm.attributeSuffix = ''
      this.editForm.strategyConditionList = []
    },
    selectMB (item, index) {
      this.editForm.strategyConditionList[index].contentTemplate =
        this.editForm.strategyConditionList[index].contentTemplate.concat(item)
      this.changeTemplate(this.editForm.strategyConditionList[index].contentTemplate, index)
      // this.changeTemplate(this.editForm.strategyConditionList[index].contentTemplate, index)
    },
    changeTemplate: function (e, itemIndex) {
      var valueData = e
      if (valueData && valueData.indexOf('@') > -1) {
        var index = valueData.lastIndexOf('@')
        var newString = valueData.slice(index).concat('}')
        console.log(this.listData.indexOf(newString), 90)
        if (this.listData.indexOf(newString) > -1) {
          console.log(valueData.slice(0, index), 9090)
          valueData = valueData.slice(0, index)
          this.editForm.strategyConditionList[itemIndex].contentTemplate = valueData.slice(0, index)
        }
      }
      var textArea = this.editForm.strategyConditionList[itemIndex].contentTemplate.replace(
        /@{监测设备}/g,
        this.editForm.eqptTypeName + '-' + this.editForm.productName
      )
      var condition = this.editForm.strategyConditionList[itemIndex]
      var type = this.getListForAttributeType(this.editForm.attributeType)
      var alarmCondition = ''
      var alarmCondition2 = ''
      type.forEach((item) => {
        if (item.value === condition.alarmCondition) {
          alarmCondition = item.label
        }
        if (item.value === condition.alarmCondition2) {
          alarmCondition2 = item.label
        }
      })
      textArea = textArea.replace(/@{监测字段}/g, this.editForm.eqptAttribute)
      textArea = textArea.replace(/@{监测单位}/g, this.editForm.attributeSuffix)
      textArea = textArea.replace(/@{触发条件一}/g, alarmCondition)
      textArea = textArea.replace(/@{触发值一}/g, condition.alarmValue)
      textArea = textArea.replace(/@{触发条件二}/g, alarmCondition2)
      textArea = textArea.replace(/@{触发值二}/g, condition.alarmValue2)
      // textArea = textArea.replace(/\@{异常值}/g, '条件');
      this.editForm.strategyConditionList[itemIndex].content = textArea
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/ .dialog-s {
  .el-dialog--center {
    min-width: 900px;
  }
}
.highlight {
  color: #1ae1e6;
}
.el-select {
  width: 100%;
}
.line {
  height: 1px;
  margin: 2px 0 10px 0;
  border-bottom: 1px dashed #cccccc;
}
.tactics-key {
  width: 180px;
}
.tactics-key-unit {
  width: 120px;
}
.cus-col-width {
  width: auto !important;
}
.cus-col-margin {
  /deep/ .el-form-item__content {
    margin-left: 10px !important;
  }
}
.order-tip {
  margin-left: 100px;
  margin-bottom: 5px;
  color: red;
}
.muBan {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  .item-list {
    margin-left: 25px;
    // width: 100px;
  }
}
</style>
